package com.its.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义 Sentinel 异常处理器类
 * 当 Sentinel 发生流控、降级、热点参数限流或权限异常时，会调用该类进行异常处理
 */
@Component
public class HandleSentinelResponseMessage implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        // 设置状态码为 429 (Too Many Requests)
        int status = 429;
        // 默认异常信息
        String message = "未知异常";
        // instanceof 是 Java 中的运算符，用于判断一个对象是否属于指定的类型。它的语法格式如下：
        if (e instanceof FlowException) {
            message = "请求被限流啦！";
        } else if (e instanceof ParamFlowException) {
            message = "请求被热点参数限流啦！";
        } else if (e instanceof DegradeException) {
            message = "请求被降级啦！";
        } else if (e instanceof AuthorityException) {
            message = "没有权限访问！";
            status = 401; // 设置状态码为 401 (Unauthorized)
        }

        // 设置响应状态码和内容类型
        response.setStatus(status);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 返回自定义的异常响应消息
        out.println("{\"status\":" + status + ",\"message\":\"" + message + "\"}");
        out.flush(); // 方法将缓冲区中的数据强制输出到目标，确保数据被立即写入到底层设备中。
        out.close(); // 方法关闭输出流，释放相关的系统资源。
    }
}
